<?php
//session_start();
//include_once $_SERVER['DOCUMENT_ROOT']."/math-videos/configure.inc.php";
//check if you have curl loaded
if(!isset($valid_controller)||$valid_controller===false)
{
  return;
}
$thumbnail ='';
$data_string = json_decode($_REQUEST['json'],true);
//$data_string = urldecode($_REQUEST['json']);
//$data_string = json_decode($data_string,true);
foreach($data_string as $key=>$value)
{
	if($key=='thumbnail')
	{
		if(is_array($value))
		{ 
		  unset($thumbnail_array);
		  foreach($value as $key2=>$value2)
			{
				$$key2 = trim($value2);
				if($key2 == 'image')
				{
					//$thumbnail_array[$key2]=urldecode($value2);
					//$thumbnail_array[$key2]=$value2;
					// echo "$key2 = $value2<br>";
					$thumbnail_array[$key2]= unserialize(gzuncompress(stripslashes(base64_decode(strtr($value2, '-_,', '+/=')))));
				}
				else
				{
					$thumbnail_array[$key2]=$value2;
				}
			}	
		}
	}
	else
	{
		$$key = trim($value);
		
//echo "!!!!!!!!!!!!!!$key = $value<br>";
	}
}
//echo "!!!!!!!!!!!!!!username = $username<br>";
//authertication user
$sqltext="select id as user_id , institute_id from users  WHERE username=? and password=?";
$params = array();

array_push($params,sql_escape($username));
array_push($params,sql_escape($password));
$result = db_select_query($conn2,$sqltext,$params);
$user_id='';
$institute_id='';
while($row = db_fetch_array($result))
{
	$user_id = $row['user_id'];
	$institute_id = $row['institute_id'];
}

if($user_id =='')
{
	header('HTTP/1.1 401 Authorization Required');
	//echo "HTTP/1.1 401 <br />";
//	echo "Date: ".gmdate('F j, Y, g:i:s')." GMT<br />";
//	echo "Location: https://api.mathinstitutes.org/metadata/v1/asset/2341<br />";
	echo "{\"error\": \"Authorization Required.\"}";
}
else
{
    //update asset table 
	$id= $assetID;
	$update_flag= false;			
	//check if user has right to upf=date this asset
	$sqltext="select title from asset WHERE id=? and institute_id = ?";
	$params = array();

	array_push($params,sql_escape($id));
	array_push($params,sql_escape($institute_id));
	$result = db_select_query($conn,$sqltext,$params);
	while($row = db_fetch_object($result))
	{
		foreach ($row as $key => $value) 
		{
			$update_flag= true;			
		}
	}
	if($update_flag)
	{			
			$params = array();
			$sqltext="UPDATE asset SET ";
			$thumbnail_sha1 ='';
			$thumbnail_sha1 = sha1($thumbnail_array['image'].$thumbnail_array['type']);
			$sqltext .="thumbnailSHA1 =?";
			 array_push($params,sql_escape($thumbnail_sha1));
			if(isset($thumbnail_array) && $thumbnail_array !='' )
			{					
				$sqltext .=",thumbnail_type =?";
				array_push($params,sql_escape($thumbnail_array['type']));
		/*		$image_name =$id."_thumb.".$thumbnail_array['type'];
			//$image_name =$id."_thumb".$thumbnail_array['type'];
				$thumbnail_image_file = $institute_id."/".$id."/".$image_name;	
				$sqltext .=",thumbnail =?";
				array_push($params,sql_escape($thumbnail_image_file));*/
			}
			else
			{
				$sqltext .=",thumbnail_type =?";
				array_push($params,sql_escape(''));
			/*	$sqltext .=",thumbnail =?";
				array_push($params,sql_escape(''));*/
			}
			$sqltext .=" WHERE id=?";
			array_push($params,sql_escape($id));
			db_change_query($conn,$sqltext,$params);
		 // echo $id;
		 
		 //update thumbnail
		 	if(isset($thumbnail_array) && $thumbnail_array !='' )
			{	
				if(!is_dir($_SERVER['DOCUMENT_ROOT']."/math-videos/images/$institute_id"))
				{
					mkdir($_SERVER['DOCUMENT_ROOT']."/math-videos/images/$institute_id", 0777); 
					mkdir($_SERVER['DOCUMENT_ROOT']."/math-videos/images/$institute_id/$id", 0777); 
				}
				elseif(!is_dir($_SERVER['DOCUMENT_ROOT']."/math-videos/images/$institute_id/$id"))
				{
					mkdir($_SERVER['DOCUMENT_ROOT']."/math-videos/images/$institute_id/$id", 0777); 
				}
				$image_name =$id."_thumb.".$thumbnail_array['type'];
				$thumbnail_image_file = $institute_id."/".$id."/".$image_name;	
				$savefile = fopen($_SERVER['DOCUMENT_ROOT']."/math-videos/images/$thumbnail_image_file", 'w');
				fwrite($savefile, $thumbnail_array['image']);
				fclose($savefile);
				//echo "#######".$site_http."images/".$thumbnail_image_file;
				//$content=	file_get_contents($site_http."images/".$thumbnail_image_file);
				//echo '<img src="data:image/".$thumbnail_array['image'].";base64,' .$content. '" />';
			}
			//add to api log
			$sqltext="INSERT INTO api_logs(query,added_date,user_id, institute_id,asset_id) values( ?, ?, ?,?,?)";
			$params = array();
			array_push($params,'Update thumbnail');
			array_push($params,date("Y-m-d H:i:s"));
			array_push($params,sql_escape($user_id));
			array_push($params,sql_escape($institute_id));
			array_push($params,sql_escape($id));
			db_change_query($conn,$sqltext,$params);
			
			unset($result_array);
			//$result_array['assetID']=$id;		
			//$result_array['assetURL']=$site_http."metadata/v1/asset/".$id;		
			$result_array['thumbnailSHA1']=$thumbnail_sha1;	
			header('HTTP/1.1 200 OK. Successful update thumbnail from asset');
			$result=json_encode($result_array);
			if(isset($_REQUEST['callback']))
			{  
			  echo $_REQUEST['callback']. '(' . $result . ');';
			  return;
			}
			echo $result;
		//	echo json_encode($result_array);
		//	echo "HTTP/1.1 200 OK <br />";
		//	echo "Date: ".gmdate('D, j F Y g:i:s')." GMT<br />";
					//echo "Content-Type: application/json<br />";
		//	echo "Location: ".$site_http."metadata/v1/asset/$id<br />";
		/*	echo "{ <br />\"assetID\": $id, <br />
									\"assetURL\": ".$site_http."metadata/v1/asset/$id\" <br />
									\"thumbnailSHA1\": \"".$thumbnail_sha1."\"<br />
									}";*/
			//return json array
			/*$result_array = array("title" => "$title", 
						"lecture_date"=> "$lecture_date",
						"remote_url" => "$remote_url",
						"organization" => "$organization",
						"presenter" => "$first_name $last_name",
						"job_title" => "$job_title",
						"keyword" => "$keyword",
						"timecode" => "$timecode",
						"timecode_type" => "$timecode_type",
						"data" =>"$data",
						"assetID" =>"$id"
						); 
			print_r($result_array);   */  
		
	}
	else
	{
		header('HTTP/1.1 403,404. Specified Asset is not owned by authenticated user and cannot be deleted, or Asset Not Found Specified Asset was not found in the catalog.');
		//echo "Date: ".gmdate('F j, Y, g:i:s')." GMT<br />";
		//	echo "Location: https://api.mathinstitutes.org/metadata/v1/asset/2341<br />";
		echo "{\"error\": \"Specified Asset is not owned by authenticated user and cannot be deleted, or Asset Not Found Specified Asset was not found in the catalog.\"}";
	}
	
}
?>